package com.gxitsky.classload.demo1;

import com.gxitsky.common.utils.RSAUtil;

import java.security.Key;
import java.util.HashMap;

/**
 * @author gxing
 * @desc 自定义类加载器
 * @date 2021/12/28
 */
public class ContainerLoader extends ClassLoader {

    /**
     * 所有加密后的文件的二进制流
     */
    private HashMap<String, byte[]> allFiles = new HashMap<String, byte[]>();

    /* 密文key */
    private Key key = null;

    public ContainerLoader(ClassLoader parent, Key key, HashMap<String, byte[]> allFiles) {
        // 这里就算是不设置 也会把自动设置父类加载器为系统加载器
        super(parent);
        this.key = key;
        this.allFiles = allFiles;
    }

    /**
     * 重写findClass方法
     *
     * @param name 是我们这个类的全路径
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        Class log = null;
        // 获取该class文件字节码数组
        byte[] classData = getData(name);

        if (classData != null) {
            // 将class的字节码数组转换成Class类的实例
            log = defineClass(name, classData, 0, classData.length);
        }
        return log;
    }

    /**
     * 获取解密后的二进制流
     *
     * @param name
     * @return
     */
    public byte[] getData(String name) {

        byte[] bytes = null;
        if (allFiles.containsKey(name)) {
            byte[] encryptBytes = allFiles.get(name);
            try {
                bytes = RSAUtil.decryptByAES(encryptBytes, key);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("error: " + name);
        }
        return bytes;

    }
}
